local LuaMongo = _G.lua_mongo
local DB = require("common.DB")
local Msg = require("core.Msg")
local os = _G.os

BroadcastList = BroadcastList or {}

local DBUpdate = {_id = nil}
local DBRemove = {_id = nil}

-- 
-- 初始
function Init()
	BroadcastList = {}
	LuaMongo.find(DB.db_adminBroadcast)
	while true do
		local tmp = {}
		if not LuaMongo.next(DB.db_adminBroadcast, tmp) then
			break
		end
		local id = tmp.id and (tmp.id .. "") or tmp._id
		BroadcastList[id] = tmp
	end
	CheckExpire()	
end


-- 添加广播
function AddBroadcast(id, type, beginDate, endDate,beginTime, endTime, interval,content)
	id = id .. ""
	if BroadcastList[id] then
		return ModifyBroadcast(id, type, beginDate, endDate,beginTime, endTime, interval, content)
	end
	-- mongodb操作后_id会被重新赋值
	BroadcastList[id] = {id = id, type = type, beginDate=beginDate,endDate=endDate, beginTime= beginTime, endTime = endTime, interval=interval,content= content }	
	LuaMongo.insert(DB.db_adminBroadcast, BroadcastList[id])
end

-- 修改广播
function ModifyBroadcast(id, type, beginDate, endDate,beginTime, endTime, interval, content)
	id = id .. ""
	if not BroadcastList[id] then		
		return AddBroadcast(id, type, beginDate, endDate,beginTime, endTime, interval,content)
	end
	BroadcastList[id].type = type
    BroadcastList[id].beginDate = beginDate
    BroadcastList[id].endDate = endDate
    BroadcastList[id].beginTime = beginTime
    BroadcastList[id].endTime = endTime
    BroadcastList[id].interval = interval
    BroadcastList[id].content = content
    
    DBUpdate._id = BroadcastList[id]._id
	LuaMongo.update(DB.db_adminBroadcast, DBUpdate, BroadcastList[id])
end

-- 删除广播
function DelBroadcast(id)	
	id = id .. ""
    if BroadcastList[id] then
		DBRemove._id = BroadcastList[id]._id
		LuaMongo.remove(DB.db_adminBroadcast, DBRemove)
        BroadcastList[id] = nil
    end
end

-- 间隔检测
function OnCheckBroadcast()
    --local curDate =  os.date("%Y%m%d") + 0
    local curDateTime = os.time()
    local curTime =  os.date("%H")*3600+os.date("%M")*60+os.date("%S")

    for k,v in pairs(BroadcastList) do
        --print("OnCheckBroadcast: curDateTime=", curDateTime, " curTime=",curTime, "v.beginDate=",v.beginDate," v.endDate=",v.endDate, " v.beginTime",v.beginTime, " v.endTime=",v.endTime)
		if curDateTime >= v.beginDate and curDateTime <= v.endDate and
            curTime >=v.beginTime and curTime <= v.endTime and
            (curTime-v.beginTime)%v.interval <10 then
             DoBroadcast(v.type, v.content)
        end
    end
end

-- 广播
function DoBroadcast(type, content)
	local msgRet = Msg.gc.GC_BROADCAST
	msgRet.type = type
	msgRet.msg = content
	Msg.sendAll(msgRet)
end


-- 删除过期的广播
function CheckExpire()
    --local curDate =  os.date("%Y%m%d", os.time())
    local curDateTime = os.time()
    for k, v in pairs(BroadcastList) do
        if v.endDate < curDateTime then
          DelBroadcast(k)
        end
    end
end

